package com.aacar.op.utils;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Random;


public final class ImageTool implements Serializable {
//    private static Logger logger = LoggerFactory.getLogger(ImageTool.class);

    private static ImageTool INSTANCE;

    static {
        INSTANCE = new ImageTool();
    }

    public static ImageTool getInstance() {
        return INSTANCE;
    }

    public String min = "min";
    public String thumbnail = "thumb";

    /**
     * 裁剪图片
     *
     * @param base    根目录
     * @param imgPath 原图片路径(虚拟路径)
     * @param left    左边的起点
     * @param top     顶部的起点
     * @param width   要裁剪的宽度
     * @param height  要裁剪的高度
     * @return String
     */
    public String cut(String base, String imgPath, int left, int top, int width, int height) {
        try {
            String suffix = imgPath.substring(imgPath.lastIndexOf(".") + 1);//后缀名
            Iterator readers = ImageIO.getImageReadersByFormatName(suffix);// 取得图片读入器
            ImageReader reader = (ImageReader) readers.next();
            InputStream source = new FileInputStream(base + imgPath);// 取得图片读入流
            ImageInputStream input = ImageIO.createImageInputStream(source);
            reader.setInput(input, true);
            ImageReadParam param = reader.getDefaultReadParam();// 图片参数
            Rectangle rect = new Rectangle(left, top, width, height);//开始裁剪
            param.setSourceRegion(rect);
            BufferedImage image = reader.read(0, param);
            String newFile = getNewPath(imgPath);
            ImageIO.write(image, suffix, new File(base + newFile));
            image.flush();
            input.flush();
            input.close();
            source.close();
            return newFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }





    // 给定范围获得一个随机颜色
    private Color getRandColor(int fc, int bc) {
        Random random = new Random();
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    // 根据原图片路径获得即将产生的路径
    private String getNewPath(String imgPath, int width, int height) {
        String filePrex = imgPath.substring(0, imgPath.lastIndexOf('.'));
        return filePrex + "_" + width + "x" + height + imgPath.substring(filePrex.length());
    }

    // 根据原图片路径获得即将产生的路径
    public String getNewPath(String imgPath, String suff) {
        if (imgPath == null) {
            return "";
        }
        String filePrex = imgPath.substring(0, imgPath.lastIndexOf('.'));
        return filePrex + "." + suff + imgPath.substring(filePrex.length());
    }

    public String getMinPath(String imgPath) {
        if (imgPath != null && !"".equals(imgPath)) {
            String filePrex = imgPath.substring(0, imgPath.lastIndexOf('.'));
            return filePrex + ".min" + imgPath.substring(filePrex.length());
        } else {
            return "";
        }
    }

    public String getNewPath(String imgPath) {
        String filePrex = imgPath.substring(0, imgPath.lastIndexOf('.'));
        return filePrex + "0" + imgPath.substring(filePrex.length());
    }


    private char mapTable[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

    private ImageTool() {

    }

    /**
     * 返回小写的图片后缀
     *
     * @param url 图片名称
     * @return
     */
    public String getSuffix(String url) {
        int endIndex = url.lastIndexOf('?');
        if (endIndex > 0) {
            url = url.substring(0, endIndex);
        }
        return url.substring(url.lastIndexOf('.') + 1).toLowerCase();
    }

    /**
     * 生成图片名称
     */
    public String getGenImageName(String type, String originalFilename) {
        return type + "_" + java.util.UUID.randomUUID().toString() + "." + getSuffix(originalFilename);
    }

    /**
     * 保存图片
     */
    public boolean saveImg(MultipartFile fileUpload, String path) throws Exception {
        File file = new File(path);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }
        FileCopyUtils.copy(fileUpload.getBytes(), file);
        return true;
    }


}
